use "$project_path/data/4_regdata/regdata", clear

log using "$project_path/output/appendix_tables/Appendix_Table_E3.smcl", replace

// Column 1 (Democracies)
rdrobust diff_m1_chix_econ runvar if subsample_democ==1, all
rdrobust std_diff_m1_hdi runvar if subsample_democ==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_democ==1, all
rdrobust diff_m1_general_chix runvar if subsample_democ==1, all

// Column 2 (Autocracies)
rdrobust diff_m1_chix_econ runvar if subsample_autoc==1, all
rdrobust std_diff_m1_hdi runvar if subsample_autoc==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_autoc==1, all
rdrobust diff_m1_general_chix runvar if subsample_autoc==1, all

// Column 3 (OECD)
rdrobust diff_m1_chix_econ runvar if subsample_oecd==1, all
rdrobust std_diff_m1_hdi runvar if subsample_oecd==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_oecd==1, all
rdrobust diff_m1_general_chix runvar if subsample_oecd==1, all

// Column 4 (non-OECD)
rdrobust diff_m1_chix_econ runvar if subsample_not_oecd==1, all
rdrobust std_diff_m1_hdi runvar if subsample_not_oecd==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_not_oecd==1, all
rdrobust diff_m1_general_chix runvar if subsample_not_oecd==1, all

// Column 5 (high time since last treatment)
rdrobust diff_m1_chix_econ runvar if subsample_elaps_last_treat_high==1, all
rdrobust std_diff_m1_hdi runvar if subsample_elaps_last_treat_high==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_elaps_last_treat_high==1, all
rdrobust diff_m1_general_chix runvar if subsample_elaps_last_treat_high==1, all

// Column 6 (low time since last treatment)
rdrobust diff_m1_chix_econ runvar if subsample_elaps_last_treat_low==1, all
rdrobust std_diff_m1_hdi runvar if subsample_elaps_last_treat_low==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_elaps_last_treat_low==1, all
rdrobust diff_m1_general_chix runvar if subsample_elaps_last_treat_low==1, all

// Column 7 (last election not treated)
rdrobust diff_m1_chix_econ runvar if last_treatment==0, all
rdrobust std_diff_m1_hdi runvar if last_treatment==0, all
rdrobust std_diff_m1_democracy_index runvar if last_treatment==0, all
rdrobust diff_m1_general_chix runvar if last_treatment==0, all

// Column 8 (last election treated)
rdrobust diff_m1_chix_econ runvar if last_treatment==1, all
rdrobust std_diff_m1_hdi runvar if last_treatment==1, all
rdrobust std_diff_m1_democracy_index runvar if last_treatment==1, all
rdrobust diff_m1_general_chix runvar if last_treatment==1, all

log close

/*
This programs tests the equality of two coefficients using the Z-test proposed by https://psycnet.apa.org/record/1995-27766-001
*/
capture program drop equality_test
program define equality_test, rclass
	args est1 est2 se1 se2
	local z = (`est1'-`est2')/sqrt((`se1')^2 + (`se2')^2)
	local pval=2*(1-normal(abs(`z')))
	local formatted_pval : di %6.3f `pval'
    return local formatted_pval = "`formatted_pval'"
end


*** Building .tex table
// Regressions 
#delimit ;
local outcomes  
		diff_m1_chix_econ
		std_diff_m1_hdi
		std_diff_m1_democracy_index
		diff_m1_general_chix
;
#delimit cr		

local subsample_count 8

// Initialize matrix of results and define value labels
local ncols = `subsample_count'*2
local nrows = 8
//Prepare matrix of coefficients and other statistics
mat Coefs = J(`nrows', `ncols', .)

mat list Coefs
	
local subsamples "_democ _autoc _oecd _not_oecd _elaps_last_treat_high _elaps_last_treat_low"

//inizialize indices
local row = 1
local next_row = `row' + 1

foreach v in `outcomes'{
	//Initialize indices
	local col = 0
	local pval_col = `subsample_count' + 0
	
	foreach sub in `subsamples'{
		
		local ++col	
		local ++pval_col
		rdrobust `v' runvar if subsample`sub' == 1, all
		
		//Store estimates and stats
		local b_`col': di %5.3f e(tau_cl)
		local se_`col': di %5.3f e(se_tau_rb)
		local p_`col': di %5.3f e(pv_rb)
	
		mat Coefs[`row',`col'] = `b_`col''
		mat Coefs[`next_row',`col'] = `se_`col''
		mat Coefs[`row',`pval_col'] = `p_`col''	
		
	}
	
	forvalues last_elec_treated=0/1{
		local ++col
		local ++pval_col
		rdrobust `v' runvar if last_treatment == `last_elec_treated'
		
		//Store estimates and stats
		local b_`col': di %5.3f e(tau_cl)
		local se_`col': di %5.3f e(se_tau_rb)
		local p_`col': di %5.3f e(pv_rb)
	
		mat Coefs[`row',`col'] = `b_`col''
		mat Coefs[`next_row',`col'] = `se_`col''
		mat Coefs[`row',`pval_col'] = `p_`col''	
	}
	
	local row = `row' + 2
	local next_row = `row' + 1
}

equality_test Coefs[7,1] Coefs[7,2] Coefs[8,1] Coefs[8,2]
local general_chix_eq_pval_democ = r(formatted_pval)
equality_test Coefs[7,3] Coefs[7,4] Coefs[8,3] Coefs[8,4]
local general_chix_eq_pval_oecd = r(formatted_pval)
equality_test Coefs[7,5] Coefs[7,6] Coefs[8,5] Coefs[8,6]
local general_chix_eq_pval_time = r(formatted_pval)
equality_test Coefs[7,7] Coefs[7,8] Coefs[8,7] Coefs[8,8]
local general_chix_eq_pval_prev = r(formatted_pval)

mat list Coefs

********************************************************************************
* 								EXPORT TABLE
********************************************************************************			
	// Clear the dataset, and use the matrix as dataset			

	clear
	svmat Coefs

	//	input variable names
	gen varname = ""
	gen temp = _n
	replace varname = "\textbf{Economic performance}" if temp == 1
	replace varname = "SE_1" if temp == 2
	replace varname = "\textbf{HDI}" if temp == 3
	replace varname = "SE_2" if temp == 4
	replace varname = "\textbf{Democracy}" if temp == 5
	replace varname = "SE_3" if temp == 6
	replace varname = "\textbf{General index}" if temp == 7
	replace varname = "SE_4" if temp == 8
	
	order varname, first
	drop temp
	  
	//Adjust the table before exporting
	replace varname = "" if strpos(varname, "SE_")>0
	order varname
	
	// Rename cols and labels
	forvalues n = 1/`subsample_count'{
		rename Coefs`n' Model`n'
	}
	//Cols where we store pvalues
	local n_min = `subsample_count' + 1
	local n_max = `subsample_count'*2
	local i = 1
	forvalues n = `n_min'/`n_max'{
		rename Coefs`n' P_Model`i'
		local ++i
	}
	
	label var varname ""
	label var Model1 "Democ."
	label var Model2 "Autoc."
	label var Model3 "Yes"
	label var Model4 "No"
	label var Model5 "High"
	label var Model6 "Low"
	label var Model7 "No"
	label var Model8 "Yes"
		
	// Convert to string and add options
	forvalues i = 1/`subsample_count'{
		tostring Model`i', replace force format(%04.3f)
		replace Model`i'= "" if Model`i'=="."
		//Add parenthesis to SE and P-val
		replace Model`i' = "(" + Model`i' + ")" if missing(varname) & Model`i' !=""	

	}
	
	// Add stars
	local 3_star 0.01
	local 2_star 0.05
	local 1_star 0.10
	
	forvalues i = 1/`subsample_count'{
		
		replace Model`i' = Model`i' + "***" if P_Model`i' < `3_star'
		replace Model`i' = Model`i' + "**" if P_Model`i' < `2_star' & P_Model`i' > `3_star'
		replace Model`i' = Model`i' + "*" if P_Model`i' < `1_star' & P_Model`i' > `2_star'
		
		drop P_Model`i'
	}
	
	foreach var of varlist _all {
	qui replace `var' = ustrtrim(`var')	
}

local title = "Heterogeneity by regime type, OECD membership, and incumbent tenure"
local filename = "baseline_het_democ_oecd_distance_elapsed_lasttreat"
local output "$project_path/output/appendix_tables/Appendix_Table_E3.tex"
local headerlines = " & \multicolumn{2}{c}{\textbf{Regime type}} & \multicolumn{2}{c}{\textbf{OECD}} & \multicolumn{2}{c}{\textbf{Time since last treat.}} & \multicolumn{2}{c}{\textbf{Last elec. treated}}"
local footnote = "\caption*{ \footnotesize \emph{Notes}: This table reports estimated effects of electoral turnovers for different subsamples. Each estimate corresponds to a separate regression. Democracies are regimes labeled as electoral democracies or liberal democracies by V-Dem. Autocracies are regimes labeled as electoral autocracies and closed autocracies by V-Dem. For OECD membership, we consider as members the 30 countries that were members of the OECD at the beginning of 2010. Time since last treat. corresponds to the number of years elapsed since last treatment. We split the sample between elections with a time since last treatment above vs. below the median, computed among elections for which the running variable is under 15 percentage points in absolute value. Last elec. treated corresponds to whether the previous election of the same type was treated or not. Using the method of \cite{clogg1995statistical}, we cannot reject the equality of the estimates for the general index for democracies and autocracies (p-val. = `general_chix_eq_pval_democ'), OECD and non-OECD countries (p-val. = `general_chix_eq_pval_oecd'), high/low time elapsed since last treatment (p-val. = `general_chix_eq_pval_time'), and for previous values of the treatment (p-val. = `general_chix_eq_pval_prev'). We obtain broadly consistent results when running a parametric regression in which we include the interaction between the treatment and the dimension of heterogeneity. $^{*} p<0.10,^{**} p<0.05,^{***} p<0.01$.}"


texsave using "`output'", replace title("`title'") varlabels noendash ///
                          footnote("`footnote'") ///
                          headerlines("`headerlines'" "& (1) & (2) & (3) & (4) & (5) & (6) & (7) & (8)" ) ///
                          frag nofix marker("tab:`filename'") location(H)
	